import React, { useEffect, useState, createRef } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { ArrowLeft, Ellipsis, Arrow } from '@react-vant/icons';
import { Image, Button, Popup, Toast } from 'react-vant';
import TopTitleBar from "../../components/TopTitleBar";
import "./index.css";
import { baseURL } from '../../utils/contants';
import axios from "../../utils/axios";
import { data } from "browserslist";
const CreateOrders = () => {
    const navigate = useNavigate();
    // const [addressId, setaddressId] = useState();
    const [settleList, setSettleList] = useState([]);
    const [totalAmount, setTotalAmount] = useState(null);
    const [showPaymentPopup, setShowPaymentPopup] = useState(false)
    const [orderNo, setOrderNo] = useState(null);

    const {
        state: { cartItemIds, addressId }
    } = useLocation();

    const [defaultAddress, setDefaultAddress] = useState({});
    // 从 “生成订单” 那里 过去 地址 管理，那么 点击 一下，就必须 设置为，订单地址，返回 生成订单页？？
    const createOrders = () => {
        setShowPaymentPopup(true)
        // 生成订单成功，然后，跳转到 我的订单 页面
        axios.post('/api/v1/saveOrder', data = {
            addressId: defaultAddress.addressId,
            cartItemIds
        }).then(res => {
            if (res.data.message === 'SUCCESS') {
                // 调起 支付 的显示 接口：支付宝 或者 微信，然后 选择相应的接口， 
                // 返回值 是一个 orderNo setOrderNo 一下：
                setOrderNo(res.data.data)
            }
        })
    }

    const handlePayment = (payType) => {
        axios.get(`/api/v1/paySuccess?orderNo=${orderNo}&payType=${payType}`).then(res => {
            if (res.data.message === 'SUCCESS') {
                // 支付成功：1. 把popup 关掉，=》 2. 弹窗：支付成功
                setShowPaymentPopup(false);
                Toast.success('支付成功')
                setTimeout(() => {
                    navigate('/myOrders', {
                        replace: true
                    })
                }, 3000)
            }
        })
    }

    const getSettle = () => {
        if (cartItemIds) {
            axios.get(`/api/v1/shop-cart/settle?cartItemIds=${(cartItemIds.map(a => a)).join(',')}`).then(res => {
                if (res.data.message === 'SUCCESS') {
                    setSettleList(res.data.data)
                    const amountsTemp = res.data.data.map(a => a.sellingPrice * a.goodsCount)
                    setTotalAmount(amountsTemp.reduce((val1, val2) => val1 + val2))
                }
            })
        }
    }
    useEffect(() => {
        getSettle();
    }, [])



    const getDefaultAddress = () => {
        axios.get('/api/v1/address/default').then(res => {
            if (res.data.message === 'SUCCESS') {
                setDefaultAddress(res.data.data)
            }
        })
    }
    const getFixAddress = () => {
        axios.get(`/api/v1/address/${addressId}`).then(res => {
            if (res.data.message === 'SUCCESS') {
                setDefaultAddress(res.data.data)
            }
        })
    }
    useEffect(() => {
        if (addressId) {
            getFixAddress();
        } else {
            getDefaultAddress();
        }

    }, [])
    // 获取 默认的 地址！

    return (
        <div className="createOrders">
            <TopTitleBar
                leftIcon={
                    <ArrowLeft onClick={() => navigate(-1)} />
                }
                intermediateContentText="生成订单"
                rightIcon={
                    <Ellipsis />
                }
            />
            <div className="mainContent">
                {
                    <div className="addressCards">
                        <div className="addressCardsLeft">
                            <div className="addressCardsLeftTop">
                                <div className="userName">
                                    {
                                        defaultAddress.userName
                                    }
                                </div>
                                <div className="userPhone">
                                    {
                                        defaultAddress.userPhone
                                    }
                                </div>

                            </div>
                            <div className="addressCardsLeftBottom">
                                {/* 左边的底部 */}
                                <div className="addressInfo">
                                    {
                                        defaultAddress.provinceName + ' ' + defaultAddress.cityName + ' ' + defaultAddress.regionName
                                    }

                                </div>
                                <div className="detailAddress">
                                    {
                                        defaultAddress.detailAddress
                                    }
                                </div>
                            </div>
                        </div>

                        <div className="addressCardsRight" onClick={() => navigate('/addressManagement', {
                            state: {
                                cartItemIds,
                                type: 'create'
                            }
                        })}>
                            {/* 点击事件，进入详情，并且，把 addressId 传过去： */}
                            <Arrow color="#27244e" />
                        </div>
                    </div>

                }

                {
                    settleList.map(product => {
                        return (
                            <div
                                key={product.cartItemId}
                                className="ShoppingCartProducts"
                            // onClick={(e) => preventDefaultChange(e)}
                            >
                                <div className="goodsImg">
                                    <Image lazyload src={String(product.goodsCoverImg).startsWith('http') ? product.goodsCoverImg : baseURL + product.goodsCoverImg} />
                                </div>
                                <div className="goodsContents">
                                    <div className="goodsRightTop">
                                        <div className="goodsTitle">
                                            {product.goodsName}
                                        </div>
                                        <div className="goodsCount">
                                            x {product.goodsCount}
                                        </div>
                                    </div>
                                    <div className="goodsRightFooter">
                                        <div className="goodsRightFooterPrice">
                                            {'¥' + product.sellingPrice}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )
                    })
                }
            </div>
            <div
                className="bottomDiv"
                onClick={createOrders}
            >
                <div className="amount">
                    <div className="lable">
                        商品金额
                    </div>
                    <div className="totalAmount">
                        {
                            '￥' + totalAmount
                        }
                    </div>
                </div>
                <Button
                    className="btn"
                    color="#1baeae"
                    text='生成订单'
                />
            </div>
            {/* <van-popup
            v-model:show="show"
            closeable
            close-icon="close"
            position="bottom"
            :style="{ height: '30%' }"  closeOnClickOverlay
            /> */}
            {
                <Popup
                    onClose={() => setShowPaymentPopup(false)}
                    closeOnClickOverlay
                    style={{ height: '30%', paddingTop: '3rem' }}
                    className='openPopup'
                    description={
                        <div className="popupBtns">
                            <div
                                className="zfbBtn"
                                style={{ marginBottom: '1rem' }}
                            >
                                <Button
                                    color="#1989fa"
                                    type="pro"
                                    text='支付宝支付'
                                    block
                                    onClick={() => handlePayment(1)}  //支付宝 传1，微信传 2
                                />
                            </div>
                            <div
                                className="wxBtn"
                            >

                                <Button
                                    color="#1baeae"
                                    text='微信支付'
                                    block
                                    onClick={() => handlePayment(2)}
                                />
                            </div>
                        </div>
                    }
                    position='bottom'
                    visible={showPaymentPopup}
                    closeable
                />
            }
        </div >
    )
}

export default CreateOrders;